#import "EventSearchView.h"

// Singleton instance of EventSearchView
static EventSearchView* sharedEventSearchView = nil;

/**
 * An EventSearchView is an object representing the view that provides
 * the complete form for searching events.
 *
 * @author      James Lin
 * @version     0.8.8
 * @since       0.8.3
 */
@implementation EventSearchView

@synthesize keywordField;
@synthesize keywordMatchControl;
@synthesize keywordString;
@synthesize matchAllKeywords;

/**
 * Retrieve the shared instance of the event search view.
 *
 * @return  the shared instance of EventSearchView
 */
+ (EventSearchView*)sharedEventSearchView {
	@synchronized(self) {
		if (sharedEventSearchView == nil) {
			sharedEventSearchView = [[EventSearchView alloc] init];
		}
		return sharedEventSearchView;
	}
}

/**
 * Allocate the event search view.
 *
 * @return  the newly allocated shared instance of EventSearchView
 */
+ (id) alloc {
	@synchronized(self) {
		sharedEventSearchView = [super alloc];
		return sharedEventSearchView;
	}
}

/**
 * Retrieve a copy of the event search view.
 *
 * @return  the shared instance of EventSearchView
 */
+ (id) copy {
	@synchronized(self) {
		return sharedEventSearchView;
	}
}

/**
 * Display the event search view.
 *
 * Pushes this view onto the navigation controller stack of the parent
 * view. Upon tapping the back button, the view is automatically 
 * popped off the top of the navigation stack.
 *
 * @param navController  the navigation controller of the parent view
 * @param delegate       the delegate handling event search results
 */
- (void)displayWithNavController:(UINavigationController*)navController
				  searchDelegate:(id<SFUEventSearchEngineDelegate>)delegate {
	searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 
																	  VIEW_WIDTH, 
																	  VIEW_HEIGHT) 
													 style:UITableViewStyleGrouped];
	
	// Set up the event search form
	self.navigationItem.title = @"Event Search";
	[searchTableView setDataSource:self];
	[searchTableView setDelegate:self];
	searchDelegate = delegate;
	parentNav = navController;
	[self.view addSubview:searchTableView];
	
	// Show the event search view
	[navController setNavigationBarHidden:NO animated:YES];
	[navController pushViewController:self animated:YES];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	// Create the segmented button for toggling keyword match mode
	keywordMatchControl = [[UISegmentedControl alloc] 
						   initWithItems:[NSArray arrayWithObjects:@"Match Any", @"Match All", nil]];
	keywordMatchControl.selectedSegmentIndex = 0;
	keywordMatchControl.segmentedControlStyle = UISegmentedControlStyleBezeled;
	keywordMatchControl.frame = CGRectMake(150, 5, 150, 30);
	keywordMatchControl.tintColor = [UIColor blackColor];
	[keywordMatchControl addTarget:self 
							action:@selector(toggleKeywordMatchMode)
				  forControlEvents:UIControlEventValueChanged];
	
	[super viewDidLoad];
}

/**
 * Set the keyboard input to search keyword field initially.
 */
- (void)viewWillAppear:(BOOL)animated {
	// Create the search keyword text field
    keywordField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 300, 30)];
	keywordField.clearButtonMode = UITextFieldViewModeWhileEditing;
	keywordField.delegate = self;
	keywordField.backgroundColor = [UIColor clearColor];
	keywordField.opaque = YES;
	keywordField.borderStyle = UITextBorderStyleRoundedRect;
	[keywordField becomeFirstResponder];
	[super viewWillAppear:animated];
}

/**
 * Hide the keyboard when view is gone.
 */
- (void)viewWillDisappear:(BOOL)animated {
	[keywordField resignFirstResponder];
	[keywordField release];
	keywordField = nil;
	[super viewWillDisappear:animated];
}

/**
 * Update the keyword match mode.
 */
- (void)toggleKeywordMatchMode {
	matchAllKeywords = ([self.keywordMatchControl selectedSegmentIndex] == 0) ? NO : YES;
}

/**
 * Traverse and set up the keyboard's return key.
 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField tag] == KeywordsField)
    {
        [textField setReturnKeyType:UIReturnKeySearch];
    }
    
    return YES;
}

/**
 * Save the information in the search form.
 */
- (void)textFieldDidEndEditing:(UITextField *)textField {
	switch ([textField tag]) {
		case KeywordsField:
			self.keywordString = [textField text];
			break;
		default:
			break;
	}
}

/**
 * Check and attempt to initiate the search upon field return.
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([textField returnKeyType] != UIReturnKeySearch) {
        NSInteger nextTag = [textField tag] + 1;
        UIView *nextField = [searchTableView viewWithTag:nextTag];
		
        [nextField becomeFirstResponder];
    } else {
		[keywordField resignFirstResponder];
		if ([keywordField.text length] > 0) {
			[[SFUEventSearchEngine sharedSearchEngine] setDelegate:searchDelegate];
			[[SFUEventSearchEngine sharedSearchEngine] findEventsWithKeywordString:keywordField.text 
																  matchAllKeywords:matchAllKeywords];
			[parentNav popViewControllerAnimated:YES];
		} else {
			UIAlertView* alertView = [[[UIAlertView alloc] initWithTitle:@"Please enter a keyword." 
																 message:@"" 
																delegate:self 
													   cancelButtonTitle:@"Ok" 
													   otherButtonTitles:nil] autorelease];
			[alertView show];
			return NO;
		}

    }
    
    return YES;
}

/**
 * Get the number of sections in the table.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {
    return 1;
}

/**
 * Get the number of rows in each section of the table.
 */
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section {
	switch (section) {
		case KeywordsGroup:
			return 2;
			break;
		default:
			return 0;
			break;
	}
}

/**
 * Get the title of each section of the table.
 */
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section {
	switch (section) {
		case KeywordsGroup:
			return @"Search for keywords:";
			break;
		default:
			return @"";
			break;
	}
}

/**
 * Update the cell content.
 */
- (UITableViewCell*)tableView:(UITableView*)tableView 
		cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    static NSString* CellIdentifier = @"SearchCellIdentifier";
	UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
									   reuseIdentifier:CellIdentifier] autorelease];
	}
	
	// Grab the cell content relevant to the section and row
    switch ([indexPath section]) {
        case KeywordsGroup:
        {
            if ([indexPath row] == 0) {
                [cell.contentView addSubview:self.keywordField];
                cell.tag = KeywordsField;
            } else {
				[cell.contentView addSubview:self.keywordMatchControl];
				cell.textLabel.text = @"Match keywords:";
				cell.textLabel.backgroundColor = [UIColor clearColor];
				cell.textLabel.font = [UIFont boldSystemFontOfSize:14.0];
				cell.tag = KeywordsMatchControl;
            }
            break; 
        }
    }
	
	// Apply aesthetic qualities to the cell
	UIView* tempView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
	tempView.backgroundColor = [UIColor clearColor];
	cell.backgroundView = tempView;
	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
	
    return cell;
}

/**
 * Deallocate the event search view.
 */
- (void)dealloc {
	[keywordString release];
	[keywordMatchControl release];
	[searchTableView release];
	[sharedEventSearchView release];
    [super dealloc];
}

@end
